import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import moment from 'moment'
import cfg from '@/config/config'
import api from '@/api/auth'
import type { PasswordForm, UserInfoForm } from '@/config/forms'
import type { UserInfo } from '@/config/types'


export const useUserStore = defineStore('user', () => {
  const loading = ref<boolean>(false)
  const userInfo = ref<UserInfo | null>(null)
  const captcha = ref<string>('')

  const user = localStorage.getItem(cfg.SYS_USER) || null
  if (user != null) {
    userInfo.value = JSON.parse(user)
  }

  const isLoggedIn = computed<boolean>(
    () =>
      userInfo.value != null &&
      userInfo.value.token != '' &&
      userInfo.value.expireTime > moment().valueOf()
  )

  const userToken = computed<string>(() => {
    if (userInfo.value != null && userInfo.value.token !== '') {
        return userInfo.value.token
    }
    return ''
  })

  async function login(username: string, password: string, code: string) {
    loading.value = true
    try {
      const res = await api.login(username, password, code)
      userInfo.value = res.data
      localStorage.setItem(cfg.SYS_USER, JSON.stringify(res.data))
      localStorage.setItem(cfg.SYS_TOKEN, res.data.token)
      localStorage.setItem(cfg.SYS_EXPIRES, res.data.expireTime)
      loading.value = false
    } catch (e) {
      loading.value = false
    }
  }

  async function loadInfo() {
    loading.value = true
    try {
      const res = await api.info()
      userInfo.value = res.data
      loading.value = false
    } catch (e) {
      loading.value = false
    }
  }

  async function refreshCaptcha() {
    try {
      const res = await api.captcha()
      captcha.value = res.data
    } catch (e) {
      captcha.value = ''
    }
  }

  function logout() {
    userInfo.value = null
    localStorage.removeItem(cfg.SYS_USER)
    localStorage.removeItem(cfg.SYS_TOKEN)
    localStorage.removeItem(cfg.SYS_EXPIRES)
  }

  async function updatePassword(form : PasswordForm) {
    loading.value = true
    try {
        await api.password(form)
        loading.value = false
        return true
    } catch (e) {
        loading.value = false
        return false
    }
  }

  async function updateInfo() {
    if (userInfo.value == null) return
    loading.value = true
    try {
        const res = await api.updateInfo({
            name: userInfo.value.name,
            avatar: userInfo.value.avatar
        } as UserInfoForm)
        loading.value = false
        if (res.data) {
            localStorage.setItem(cfg.SYS_USER, JSON.stringify(userInfo.value))
        }
        return res.data
    } catch(e) {
        loading.value = false
    }
    return false
  }

  return {
    loading,
    isLoggedIn,
    userInfo,
    userToken,
    captcha,

    login,
    logout,
    loadInfo,
    refreshCaptcha,
    updatePassword,
    updateInfo
  }
})
